
var treeMap, html='';
function treeData(obj){
	
	var wx =  (obj.state == '02')?'xw':''
	html += '<div class="items"><div class="child '+wx+'" id="child'+obj.userId + '"phone="'+obj.phone
	+'" userId='+obj.userId+'><div class="child-data"><p>'
	+obj.realName+'</p><p><span>'+obj.addConsume+'</span></p></div></div>';
	var childs = obj.allChilds;
	for(var i = 0; i< childs.length; i++){
		console.log(childs[i])
		if(childs[i] in treeMap){
			treeData(treeMap[childs[i]]);
		}
	}
	html += '</div>'
}

function tree() {
	  var canvas = document.querySelector('#canvas');
	  var ctx = canvas.getContext('2d');
	  var screenWh = document.documentElement.clientWidth
	  var screenHt = document.body.scrollHeight
	  canvas.width = screenWh
	  canvas.height = screenHt
	  if (window.devicePixelRatio) {
	    canvas.style.width = screenWh + "px";
	    canvas.style.height = screenHt + "px";
	    canvas.width = screenWh * window.devicePixelRatio;
	    canvas.height = screenHt * window.devicePixelRatio;
	    ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
	  }
	  ctx.clearRect(0, 0, screenWh, screenHt)
	  var initEle = document.querySelector('.items')
	  coordinate(initEle, 0, 0)
	  function draw(x, y, endX, endY) {
	    ctx.beginPath();
	    ctx.moveTo(x, y);
	    ctx.lineWidth = 1;
	    ctx.lineTo(endX, endY);
	    ctx.stroke();
	  }
	  function coordinate(item, prevLeft, prevTop) {
	    var childs = item.children;
	    var ele = childs[0]
	    var left = ele.getBoundingClientRect().left + ele.offsetWidth / 2
	    var top = ele.getBoundingClientRect().top + ele.offsetWidth / 2
	    if (prevLeft !== 0 && prevTop !== 0) { draw(prevLeft, prevTop, left, top) }
	    for (var i = 1; i < childs.length; i++) {
	      coordinate(childs[i], left, top)
	    }
	  }
	}

window.addEventListener('resize', function () {
	  tree()
})


//layer.tips('默认就是向右的', '#id或者.class');

var index;
$('body').on('mouseenter','.child',function(){
	
	 index= layer.tips('手机号:'+$(this).attr('phone'), '#'+$(this).attr('id'));
})

$('body').on('mouseleave','.child',function(){
	
	 layer.close(index)
	 
})


$('body').on('click','.child',function(){
	$this = $(this);
	layer.open({
		  title:'提示', 
		  content:'请选择',
		  btn: ['查看子节点','添加子节点','变更节点'],
		  btn1: function(){
			  userId = $this.attr('userId');
			  $('#tree').empty();
			  data();
			  layer.msg(userId, {icon: 1});
		  },
		  btn2: function(){
			layer.confirm('手机号：<input type="text" id="phone"/>',{
			  btn: ['确定'] //按钮
				},function(){
				var phone = $('#phone').val();
				add($this.attr('userId'),phone);
				});
	
		  },
		  btn3: function(){
			layer.confirm('<p>变更节点会初始化公排，请慎用。</p><p>手机号：<input type="text" id="phone"/></p>',{
				  btn: ['确定'] //按钮
					},function(){
					var phone = $('#phone').val();
					update($this.attr('userId'),phone);
					});
		 }
	});
})